<?php

namespace App\Models\Train\TrainQuery;

use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

/**
 * App\Models\Train\TrainQuery\TrainQueryLog
 *
 * @property int         $id
 * @property string      $from_code  出发站
 * @property string      $from_type  出发站类型
 * @property string      $to_code    目的站
 * @property string      $to_type    目的站类型
 * @property string      $date       查询日期
 * @property string      $count      查询次数
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property string      $ip_address ip 地址
 * @method static Builder|TrainQueryLog newModelQuery()
 * @method static Builder|TrainQueryLog newQuery()
 * @method static Builder|TrainQueryLog query()
 * @method static Builder|TrainQueryLog whereCount($value)
 * @method static Builder|TrainQueryLog whereCreatedAt($value)
 * @method static Builder|TrainQueryLog whereDate($value)
 * @method static Builder|TrainQueryLog whereFromCode($value)
 * @method static Builder|TrainQueryLog whereFromType($value)
 * @method static Builder|TrainQueryLog whereId($value)
 * @method static Builder|TrainQueryLog whereIpAddress($value)
 * @method static Builder|TrainQueryLog whereToCode($value)
 * @method static Builder|TrainQueryLog whereToType($value)
 * @method static Builder|TrainQueryLog whereUpdatedAt($value)
 * @mixin Eloquent
 */
class TrainQueryLog extends Model
{
    use HasFactory;

    protected $table = 'train_query_logs';
    protected $fillable
                     = [
            'from_code',
            'from_type',
            'to_code',
            'to_type',
            'date',
            'count',
            'ip_address',
        ];

    public function createOrUpdate($data)
    {
        $res = $this
            ->where('from_code', $data['from_code'])
            ->where('to_code', $data['to_code'])
            ->where('date', $data['date'])
            ->where('ip_address', $data['ip_address'])
            ->first();
        if ($res) {
            if ($res->count < $data['count']) {
                $res->update($data);
            }
            return $res;
        }
        return $this->create($data);
    }
}
